package com.qf.shoppingorder.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.shoppingorder.entity.Order;
import com.qf.shoppingorder.mapper.OrderMapper;
import com.qf.shoppingorder.util.CacheManagerSevice;
import entity.ResultData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMDDHHmmss");
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    CacheManagerSevice cacheManagerSevice;

    @Autowired
    RabbitTemplate rabbitTemplate;

//    @Autowired
//    ProductService productService;

    //    todo 测试远程调用
    @GetMapping("/test")
    public ResultData ttt() {
//        return productService.a();
        return null;
    }

    @GetMapping("/all")
    public ResultData all(Integer userId) {
        QueryWrapper<Order> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        List<Order> all = orderMapper.selectList(qw);
        for (int i = 0; i < all.size(); i++) {
            Order order = all.get(i);
            if ("0".equals(order.getStatus())) {
                long expire = cacheManagerSevice.getExpire("order_" + order.getOrderNumber());
                if (expire == -2L) {
                    order.setStatus("-1");
                } else {
                    order.setExpirationTime(expire);
                }
//                order.setExpirationTime();
            }
        }
        return new ResultData<List>(true, all);
    }

    @PostMapping("/produce")
    @Transactional(rollbackFor = Exception.class)
    public ResultData produce(@RequestBody Order order) {
        /**
         *          库存<=0   ===>售罄
         *         查询商品库存
         *         库存>0
         *         订单生成,库存-1  ===加锁
         *         过期===>商品库存+1 ==>解锁
         */
        Date date = new Date();
        // 创建Calendar对象，并设置为当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // 将时间增加2分钟
        calendar.add(Calendar.MINUTE, 2);
        // 获取增加2分钟后的时间
        Date expirationTime = calendar.getTime();
        order.setOrderNumber(order.getUserId().toString() + System.currentTimeMillis());
        order.setCreateTime(sdf.format(date));
        order.setStatus("0");
        order.setExpirationTime(30L);
        int insert = orderMapper.insertOrder(order);
//        productService.decrease(order.getProductId());
//        Product product1 = (Product) decreaseData.getData();
        if (insert > 0) {
            cacheManagerSevice.sSetAndTime("order_" + order.getOrderNumber(), 30L, JSON.toJSONString(order));
            rabbitTemplate.convertAndSend("delay-exchange", "delay-route", order);
            return new ResultData<>(true, "下单成功");
        } else {
            return ResultData.fail("下单失败");
        }
    }

    @PostMapping("/del")
    public ResultData del(@RequestBody Order order) {
        int delete = orderMapper.deleteById(order.getId());
        if (delete > 0) {
            return new ResultData<Object>(true, "删除成功");
        } else {
            return ResultData.fail("删除失败");
        }
    }
}
